#include "main.h"

void start_local_game()
{
    Game *server = game_server_spawn();

    game_client_connect_local(server);
    game_client_connect_local(server);

    game_deathmatch_setup(server);

    game_server_start(server);

    server->currentPlayerIndex = 0 ;

    while(1)
    {
        io_player_read_actions();
        for(int i = 0; i < array_size(server->localPlayers); i++)
        {
            Game_Player *p = &server->players[server->localPlayers[i]];
            p->actions = io_player_get_actions(i);
        }

        if(game_server_ticks(server)) break;

        gfx_scene_begin();
        game_draw(server);
        gfx_scene_end();
        time_sleep(1./60);
    }

    game_delete(server);
}

void start_simple_game()
{
    Game *server = game_server_spawn();

    Game_Player *p1 = game_player_spawn(server);
    Game_Entity *e1 = &server->entities[p1->entityIndex];

    server->localPlayers = array_resize(server->localPlayers, 1);
    server->localPlayers[0] = p1->playerIndex;

    game_sample_setup(server);

    e1->sprite.image = gfx_image_get("game_player1");

    game_server_start(server);

    while(1)
    {
        io_player_read_actions();

        p1->actions = io_player_get_actions(0);

        if(game_server_ticks(server)) break;

        gfx_scene_begin();
        game_draw(server);
        gfx_scene_end();
        time_sleep(1./60);
    }

    game_delete(server);
}

int main(int argc, char *argv[])
{
    base_init();    atexit(base_exit);
    gfx_init();     atexit(gfx_exit);
    //sfx_init();     atexit(sfx_exit);
    io_init();      atexit(io_exit);
    net_init();     atexit(net_exit);

    tcp_socket *s = tcp_socket_connect("localhost", 21);
    char buf[4096];

    time_sleep(1);
    memset(buf, 0, sizeof(buf));
    tcp_socket_recv(s, buf, sizeof(buf));
    fputs(buf, stderr);

    tcp_socket_send(s, "QUIT\n", sizeof("QUIT"));
    time_sleep(1);

    memset(buf, 0, sizeof(buf));
    tcp_socket_recv(s, buf, sizeof(buf));
    fputs(buf, stderr);
    tcp_socket_close(s);

    return 0;
}

int _main(int argc, char *argv[])
{
    base_init();    atexit(base_exit);
    gfx_init();     atexit(gfx_exit);
    sfx_init();     atexit(sfx_exit);
    io_init();      atexit(io_exit);

    GFX_Resolution res;
    res.width = 640;
    res.height = 480;
    res.bpp = 32;
    res.fullscreen = 0;
    gfx_set_resolution(res);

    io_load_ressources();

    gui_menu_main();

    return 0;
}
